package com.jm.member.common.jwt.ignore;

import com.jm.member.common.jwt.annon.IgnoreUrlsAnnon;
import org.springframework.beans.BeansException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.PostConstruct;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;


@Component("ignorePostProcess")
@Order
@ConditionalOnClass(RequestMappingHandlerMapping.class)
public class IgnorePostProcess implements ApplicationContextAware {

    private ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            this.context=applicationContext;
    }

    @PostConstruct
    public void init(){
        RequestMappingHandlerMapping bean = context.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = bean.getHandlerMethods();
        Set<Map.Entry<RequestMappingInfo, HandlerMethod>> entries = handlerMethods.entrySet();
        Iterator<Map.Entry<RequestMappingInfo, HandlerMethod>> iterator = entries.iterator();

        while (iterator.hasNext()){
            Map.Entry<RequestMappingInfo, HandlerMethod> next = iterator.next();
            HandlerMethod value = next.getValue();
            IgnoreUrlsAnnon methodAnnotation = value.getMethodAnnotation(IgnoreUrlsAnnon.class);
            if(methodAnnotation!=null){
                IgnoreProperties.ignoreUrls.add(methodAnnotation.value());
            }
        }
    }

}
